import { Component, Label, RichText, size, tween, UIOpacity, v3, view, _decorator } from "cc";
import { EventConst } from "../Common";
import { App } from "./../../App";

const { menu, ccclass, property, disallowMultiple } = _decorator;
@ccclass('MessageBox')
@disallowMultiple
@menu("自定义插件/通用弹出对话框")
export default class MessageBox extends Component {
    @property({ type: Label, tooltip: '弹框标题' })
    lblTitle: Label = null;
    @property({ type: RichText, tooltip: '弹框消息文本' })
    lblMBtext: RichText = null;
    @property({ type: Label, tooltip: '确认按钮文本' })
    lblOK: Label = null;
    @property({ type: Label, tooltip: '取消按钮文本' })
    lblCancel: Label = null;
    @property({ type: Label, tooltip: '其他按钮文本' })
    lblOther: Label = null;

    private _msgBtnText: string[] = [];
    private _callBack:(id:number)=>void;
    private _canvasSize = size(0,0);

    /**
     * init
     */
    public init() {
        App.Event.on(EventConst.POP_MSG_BOX,(text: string, call?: (flag: number) => void)=>{
            let txts = text.split('|');
            if (txts.length < 3) return ;
            
            this.lblTitle.string = txts[0];
            this.lblMBtext.string = txts[1];
            App.opacity(this,0);
            this.node.scale = v3(1,1,0);
            this.node.active = true;
    
            // 设置按钮显示文本
            if (txts.length === 4) {
                this.lblOK.string = txts[2];
                this.lblCancel.string = txts[3];
                App.position(this.lblOK.node.parent,-150);
                App.position(this.lblCancel.node.parent,-150);
                this.lblOK.node.parent.active = true;
                this.lblCancel.node.parent.active = true;
            } else if (txts.length === 3){
                this.lblOK.string = txts[2];
                App.position(this.lblOK.node.parent,0);
                this.lblOK.node.parent.active = true;
                this.lblCancel.node.parent.active = false;
            }
            const opa:UIOpacity = this.getComponent(UIOpacity);
            tween(opa).to(0.2,{opacity:255},{easing:'quadIn'}).start();
            this._callBack = call;
        },this);
    }

    start () {
        this._callBack = null;
        this._msgBtnText[0] = this.lblOK.string;
        this._msgBtnText[1] = this.lblCancel.string;
        this._canvasSize = view.getVisibleSize();
        !this.getComponent(UIOpacity) && this.addComponent(UIOpacity);
    }

    onClick(_: any, userData: any) {
        const opa:UIOpacity = this.getComponent(UIOpacity);
        tween(opa)
        .to(0.2,{opacity:0},{easing:'quadOut'})
        .call(()=>{
            this._callBack && this._callBack(parseInt(userData));
            this._callBack = null;
            this.node.scale = v3(0,0,0);
            this.node.active = false;
            tween(this).stop();
        }).start();
    }
}
